import json
import types
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from django.conf import settings


class TencentSMS:
    """
    腾讯云短信服务封装累，用于发送短信
    """

    def __init__(self):
        """
        初始化腾讯云短信客户端
        使用Django配置中的 SecretId 和 SecretKey进行认证
        """
        # 使用django配置中的SecretId 和 SecretKey创建认证对象
        self.cred = credential.Credential(settings.TENCENT_SMS['SecretId'], settings.TENCENT_SMS['SecretKey'])

        # 配置HTTP请求选项
        httpProfile = HttpProfile()
        httpProfile.endpoint = "sms.tencentcloudapi.com"

        # 配置客户端选项
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile

        # 创建短信客户端对象
        self.client = sms_client.SmsClient(self.cred, settings.TENCENT_SMS['REGION'], clientProfile)

    def sms_code(self, phone_number, template_param_set):
        """

        :param phone_number: 接收短信的手机号码
        :param template_param_set: 短信模版参数列表(验证码)
        :return: 返回短信发送结果的json字符串，如果发送异常则返回错误信息
        """
        try:
            #     创建短信发送请求对象
            req = models.SendSmsRequest()

            # 设置请求参数
            params = {
                "PhoneNumberSet": [phone_number],
                "SmsSdkAppId": settings.TENCENT_SMS['SMS_SDK_APP_ID'],
                "TemplateId": settings.TENCENT_SMS['TEMPLATE_ID'],
                "SignName": settings.TENCENT_SMS['SIGN_NAME'],
                "TemplateParamSet": [template_param_set]
            }
            # json.dumps(params) 将字典转换成json格式
            req.from_json_string(json.dumps(params))
            # 发送短信并获取响应
            resp = self.client.SendSms(req)

            #  返回响应结果的JSON字符串
            return resp.to_json_string()

        except TencentCloudSDKException as err:
            return str(err)
